(function($) {
    $.cookie = function(key, value, options) {

        // key and at least value given, set cookie...
        if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) {
            options = $.extend({}, options);

            if (value === null || value === undefined) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || {};
        var decode = options.raw ? function(s) { return s; } : decodeURIComponent;

        var pairs = document.cookie.split('; ');
        for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
            if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
        }
        return null;
    };
})(jQuery);


function login(user_id, password, callback) {
	$.ajax({
		type: "POST"
		,url: "http://143.248.133.215:8085/pickytest/login"
		,data: {"user_id":user_id,"password":password}
		,dataType: "json"
		,success: function(a,b,c){callback(a);}
		,error: function(er,ee){console.log("err: "+ee);}
		});
}

function register(username, password, photo_url, description, user_id, callback) {
	//console.log("registering");
	$.ajax({
		type: "POST"
		,url: "http://143.248.133.215:8085/pickytest/register"
		,data: {"username":username, "password":password, "photo_url":photo_url, "description":description, "user_id":user_id}
		,dataType: "json"
		,success: function(a,b,c){callback(a);}
		,error: function(er,ee){console.log("err: "+ee);}
		});
}

function logout(user_id,access_token, callback){
	 $.ajax({
			type: "POST"
			,url: "http://143.248.133.215:8085/pickytest/logout"
			,data: {"user_id":user_id,"access_token":access_token}
			,dataType: "json"
			,success: function(a,b,c){callback(a);}
			,error: function(er,ee){console.log("err: "+ee);}
			});
}

function new_survey(title, description, category_id, user_id, callback) {
	 $.ajax({
			type: "POST"
			,url: "http://143.248.133.215:8085/pickytest/new_survey"
			,data: {"user_id":user_id, "title":title, "description":description, "category_id":category_id}
			,dataType: "json"
			,success: function(a,b,c){callback(a);}
			,error: function(er,ee){console.log("err"+ee);}
			});
}


function upload_photo(data, callback) {
	$.ajax({
	type: "POST"
	,url: "http://143.248.133.215:8085/pickytest/upload"
	,data: {"data":data}
	,dataType: "json"
	,success: function(a,b,c){callback(a.upload.links.small_square);}//
	,error: function(er,ee){console.log("err: "+ee);}
	});	
}

function new_option(photo_url, description, survey_id, callback) {
	 $.ajax({
			type: "POST"
			,url: "http://143.248.133.215:8085/pickytest/new_option"
			,data: {"photo_url":photo_url, "description":description, "survey_id":survey_id}
			,dataType: "json"
			,success: function(a,b,c){callback(a);}
			,error: function(er,ee){console.log("err: "+ee);}
			});
}

function activate_survey(survey_id, callback) {
	 $.ajax({
			type: "POST"
			,url: "http://143.248.133.215:8085/pickytest/activate_survey"
			,data: {"survey_id":survey_id}
			,dataType: "json"
			,success: function(a,b,c){callback(a);}
			,error: function(er,ee){console.log("err: "+ee);}
			});
}

function vote(option_id, callback) {
	 $.ajax({
			type: "POST"
			,url: "http://143.248.133.215:8085/pickytest/vote"
			,data: {"option_id":option_id, "user_id":user_id}
			,dataType: "json"
			,success: function(a,b,c){callback(a);}
			,error: function(er,ee){console.log("err: "+ee);}
			});
}

function search_survey(category_id, relationship, keyword, from, sort, callback) {
	// console.log(sort);
	 $.ajax({
			type: "POST"
			,url: "http://143.248.133.215:8085/pickytest/search_survey"
			,data: {"category_id":category_id, "relationship":relationship, "keyword":keyword, "from":from, "sort": sort}
			,dataType: "json"
			,success: function(a,b,c){callback(a);}
			,error: function(er,ee){console.log("err: "+ee);}
			});
}

function get_survey(survey_id, callback) {
	 $.ajax({
			type: "POST"
			,url: "http://143.248.133.215:8085/pickytest/get"
			,data: {"survey_id":survey_id}
			,dataType: "json"
			,success: function(a,b,c){callback(a);}
			,error: function(er,ee){console.log("err: "+ee);}
			});
}

function profile(user_id, callback) {
	$.ajax({
		type: "POST"
		,url: "http://143.248.133.215:8085/pickytest/profile"
		,data: {"user_id":user_id}
		,dataType: "json"
		,success: function(a,b,c){callback(a);}
		,error: function(er,ee){console.log("err: "+ee);}
		});
}

function search_user(username, callback) {
	$.ajax({
		type: "POST"
		,url: "http://143.248.133.215:8085/pickytest/search_user"
		,data: {"username":username}
		,dataType: "json"
		,success: function(a,b,c){callback(a);}
		,error: function(er,ee){console.log("err: "+ee);}
		});
}


function get_category(callback) {
  $.ajax({
   type: "POST"
   ,url: "http://143.248.133.215:8085/pickytest/get_category"
   ,data: {}
   ,dataType: "json"
   ,success: function(a,b,c){callback(a);}
   ,error: function(er,ee){console.log("err: "+ee);}
   });
}

function update_category(id_select) {
	get_category(function(o){
		var s =  '<option value="0" selected=true>Category: All</option>';
		for (var i=0; i<o.categories.length; i++) {
			e=o.categories[i];
			s+= '<option value="' + e.category_id + '">Category: ' + e.category_name + '</option>';
		}
		cat = $(id_select).html(s);
		cat.val('0');
		cat.selectmenu('refresh');
		cat.trigger('change');
		
	});
}

function delete_survey(surveyid,callback){
	$.ajax({
		   type: "POST"
		   ,url: "http://143.248.133.215:8085/pickytest/delete_survey"
		   ,data: {"survey_id":surveyid}
		   ,dataType: "json"
		   ,success: function(a,b,c){callback(a);}
		   ,error: function(er,ee){console.log("err: "+ee);}
		   });
}

function follow(follower,following,callback){
	$.ajax({
		   type: "POST"
		   ,url: "http://143.248.133.215:8085/pickytest/follow"
		   ,data: {"follower":follower, "following":following}
		   ,dataType: "json"
		   ,success: function(a,b,c){callback(a);}
		   ,error: function(er,ee){console.log("err: "+ee);}
		   });
}

function get_follow(uid,callback){
	$.ajax({
		   type: "POST"
		   ,url: "http://143.248.133.215:8085/pickytest/get_follow"
		   ,data: {"user_id":uid}
		   ,dataType: "json"
		   ,success: function(a,b,c){callback(a);}
		   ,error: function(er,ee){console.log("err: "+ee);}
		   });
}

function post_comment(sid,uid,purl,comm,callback){
	$.ajax({
		   type: "POST"
		   ,url: "http://143.248.133.215:8085/pickytest/post_comment"
		   ,data: {"survey_id":sid, "user_id":uid, "photo_url":purl, "comment":comm}
		   ,dataType: "json"
		   ,success: function(a,b,c){callback(a);}
		   ,error: function(er,ee){console.log("err: "+ee);}
		   });
}

function get_comment(sid,callback){
	$.ajax({
		   type: "POST"
		   ,url: "http://143.248.133.215:8085/pickytest/get_coomment"
		   ,data: {"survey_id":sid}
		   ,dataType: "json"
		   ,success: function(a,b,c){callback(a);}
		   ,error: function(er,ee){console.log("err: "+ee);}
		   });
}

$('#loadingDiv')
	.hide()
	.ajaxStart(function() {
		$(this).hide();
	})
	.ajaxStop(function() {
		$(this).hide();
	});

function updateMainList() {
	search_survey($("#mainCat")[0].value,"or","GSGHWRIOO",0,sort_type,function(a){
			//console.log(a.surveys);
			var list = $("#mainList").empty();
			for (var i=0; i<a.surveys.length; i++) {
				var o=a.surveys[i].survey;
				 var s='<li data-theme="c"><a data-transition="slide" href="';
				s += '#survey" onclick="survey_id='+ o.survey_id +'" >' + o.title + '</a></li>';
				list.append(s);
			}
			list.listview('refresh');
			 
		});
}
		
$( '#main' ).live( 'pagebeforeshow',function(event, object){
	//set on change function of cat
	$("#mainCat").change(function(e) {
		updateMainList();
	});
	update_category("#mainCat");
});

function voteIt(option_id) {
	if (user_id=="") alert("not logged in");
	else{
		vote(option_id,function(d) {
			alert(d.msg);
			updateOptionList();
		});
	}
}

function updateOptionList() {
	get_survey(survey_id,function (d){
		survey_user_id=d.user_id;
		var list=$("#surveyList").empty();
		// console.log(d);
		$("#surveyAvaSrc").attr("src",d.photo_url);
		$("#surveyTitle").text(d.title);
		$("#surveyDescription").text(d.description);
		$("#surveyAuthorDate").text("Posted by " + d.user_id + " in category " + d.category.category_name);
		var s='<li data-role="list-divider">Options:</li>';
		for (var i=0; i<d.options.length; i++) {
			e=d.options[i];
			//console.log(e);
			s+='<li data-icon="check"><a href="#" onclick="voteIt('+e.option_id+')">';
			s+='<img src="'+ e.photo_url + '" />';
			s+='<h3>'+e.description+'</h3>';
			s+='<span class="ui-li-count">'+e.vote+'</span>';
			s+='</a></li>';
		}
		list.append(s).listview('refresh');
	});
}

function updateCommentList() {
	get_comment(survey_id,function (d){
		//survey_user_id=d.user_id;
		var list=$("#commentList").empty();
		
		var s='<li data-role="list-divider">Comments:</li>';
		for (var i=0; i<d.comments.length; i++) {
			e=d.comments[i];
			//console.log(e);
			
			s+='<li><table cellpadding="3" width="270" style="word-break:break-word;">';
			s+='<tr><td width="70"><img style="width: 50px; height: 50px" src="'+ e.photo_url + '" />';
			s+='<br>'+e.user_id+'</td>';
			s+='<td width="200">'+e.comment+'</td>';
			s+='</tr></table></li>';
		}
		
		list.append(s).listview('refresh');
		

		
	});
}

$

$('#survey').live('pagebeforeshow',function(event,object) {
	updateOptionList();
	//console.log(object);
	updateCommentList();
});

$('#add').live('pagebeforeshow',function(event,object) {
	if (!user_id) {
		window.location.href="#login";
	}
	else{
		profile(user_id, function(d){
			$("#add_user_id").html(user_id);
			$("#add_username").html('( '+d.username+' )');
			var profimg = document.getElementById('add_photo_url');
			profimg.src = d.photo_url;

			update_category("#selectmenu3");
			$("#div2").html("");
		});
	}
		
});


$('#profile').live('pagebeforeshow',function(event,object) {
	//console.log(user_id);
	if (!($.cookie('user_id'))) {
		window.location.href="#login";
		return;
	}
	if (!user_id) {
		user_id = $.cookie('user_id');
	}
		get_category(function (cat){
			var catarray = new Array(10);
			for (var i=0;i<cat.categories.length;i++){
				catarray[cat.categories[i].category_id]=cat.categories[i].category_name;
			}
			get_follow(user_id,function(f){
			
				profile(user_id, function (d) {
					//console.log(d);
					user_obj = d;
					$("#user_id").html(user_id);
					$("#username").html('( '+d.username+' )');
					var profimg = document.getElementById('photo_url');
					profimg.src = d.photo_url;
					$("#profdesc").html(d.description);
					
					var list = $("#profileList").empty();
					var catid=-1;
					for (var i=0; i<d.surveys.length; i++) {
						var o=d.surveys[i];
						var curcid=parseInt(o.category_id);
						if (catid != curcid){
							catid = curcid;
							var s2 = '<li data-role="list-divider" role="heading">'+catarray[catid]+'</li>';
							list.append(s2);
						}
						
						 var s='<li data-theme="c"><a data-transition="slide" href="';
						s += '#survey" onclick="survey_id='+ o.survey_id +'" >' + o.title + '</a></li>';
						list.append(s);
					}
					
					var list2 = $("#followList").empty();
					for (var i=0; i<f.followings.length; i++) {
						var o=f.followings[i];					
						
						 var s='<li data-theme="c"><a data-transition="slide" href="';
						s += '#f_profile" onclick="f_user_id='+ "'"+o+"'" +'" >' + o + '</a></li>';
						list2.append(s);
					}
					
					list.listview('refresh');				
					list2.listview('refresh');
				});
			});
		});
});

$('#f_profile').live('pagebeforeshow',function(event,object) {
	//alert(user_id);
	//console.log(f_user_id);
	if (!f_user_id) {
		window.location.href="#login";
	} else {
		get_category(function (cat){
			var catarray = new Array(10);
			for (var i=0;i<cat.categories.length;i++){
				catarray[cat.categories[i].category_id]=cat.categories[i].category_name;
			}
			get_follow(f_user_id,function(f){
			
				profile(f_user_id, function (d) {
					console.log(d);
					$("#f_user_id").html(d.user_id);
					$("#f_username").html('( '+d.username+' )');
					var profimg = document.getElementById('f_photo_url');
					profimg.src = d.photo_url;
					$("#f_profdesc").html(d.description);
					
					var list = $("#f_profileList").empty();
					var catid=-1;
					for (var i=0; i<d.surveys.length; i++) {
						var o=d.surveys[i];
						var curcid=parseInt(o.category_id);
						if (catid != curcid){
							catid = curcid;
							var s2 = '<li data-role="list-divider" role="heading">'+catarray[catid]+'</li>';
							list.append(s2);
						}
						
						 var s='<li data-theme="c"><a data-transition="slide" href="';
						s += '#survey" onclick="survey_id='+ o.survey_id +'" >' + o.title + '</a></li>';
						list.append(s);
					}
					
					var list2 = $("#f_followList").empty();
					for (var i=0; i<f.followings.length; i++) {
						var o=f.followings[i];					
						
						 var s='<li data-theme="c"><a data-transition="slide" href="';
						s += '#f_profile" onclick="f_user_id='+ o +'" >' + o + '</a></li>';
						list2.append(s);
					}
					
					list.listview('refresh');				
					list2.listview('refresh');
				});
			});
		});
	}
});





$(document).on('pageshow', '[data-role="page"]', function (event, obj) {
    // var list= $('.ui-page-active [data-role="footer"] a');
    // list.removeClass('ui-btn-active');
    // for (var i=0; i<list.length; i++) {
    	//console.dir(list[i].firstElementChild);
    	// if ($.trim(list[i].innerText.toLowerCase())==$.mobile.activePage[0].id) 
    		// list[i].addClass('ui-btn-active');
    	// else 
    		// list[i].removeClass('ui-btn-active');
    // }
});







var blankimg="http://i.imgur.com/KgqHf.jpg";
var newphotourl="";
var optcnt=0;

function refreshAdd(){
	//refresh the page "Add"
	$("#div1").show('fast');
	$("#div2").hide('fast');
	
	$("#div3").hide('fast');
	$("#div4").hide('fast');
	//$("#selectmenu3").val()=0;
	
	textinput3.value="";
	//textinput3.placeholder="Survey's Title";
	
	textarea3.value="";
	//textarea3.placeholder="Survey's Description";
	
	$("#div2").empty();
	$("#div3").empty();
	
}

function activcb(){
	refreshAdd();
	window.location.href="#survey";
}

function doActivate(){
	activate_survey(survey_id,activcb);
}

function deletecb(a){
	refreshAdd();
	window.location.href="#main";
}

function cancelAdd(){
	delete_survey(survey_id,deletecb);
	
}

function save_sid(result){
	survey_id=result.survey_id;
	$("#div1").hide('fast');
	$("#div2").show('fast');
	
	$("#div3").show('fast');
	$("#div4").show('fast');
}


function uploadOpt(){
	var odesc = $("#textinput4").val();
	if (newphotourl=="") alert("Please insert information!");
	else{
		$("#waiting").show('fast');
		$.blockUI();
		new_option(newphotourl,odesc,survey_id,showOpt);
	}
}

function showOpt(a){
	var nopt = document.createElement("div");
	var odesc = $("#textinput4").val();
	var nid = "opt"+optcnt;
	//var nnid = "tbl"+optcnt;
	optcnt++;
	
	//nopt.setAttribute('data-role','collapsible');
	//nopt.setAttribute('data-collapsed','false');
	nopt.setAttribute('id',nid);
	document.getElementById("div3").appendChild(nopt);
	$("#"+nid).append("<table class='mceItemTable' border='0'><tbody><tr>");
	$("#"+nid).append("<td><p><strong><img src='"+newphotourl+"' width='100' height='100' /></strong></p></td>");
	$("#"+nid).append('<td><p style="margin-left: 30px; " data-mce-style="margin-left: 30px;">'+odesc+"</p></td>");
	$("#"+nid).append("</tr></tbody></table>");
	//$("#opt0").append("dfsdg");
	
	var smallImage = document.getElementById('smallImage');

	smallImage.src = blankimg;
	textinput4.value="";
	newphotourl="";
	$("#waiting").hide('fast');
	$.unblockUI();
	
}


function regSurvey(){
	//console.log("a");
	//find optionid and call js
	var stitle=$("#textinput3").val();
	var sdesc=$("#textarea3").val();
	var catid=$("#selectmenu3").val();
	if (catid == 0){alert("Please select category!")}
	else{
		new_survey(stitle,sdesc,catid,user_id,save_sid);
		//new_survey("newt","newd",1,user_id,save_sid);
		$("#div2").append("<p style='margin-left: 30px; '><h1>"+stitle+"</h1></p><p style='margin-left: 30px; '><span style='font-size: x-small; '>"+sdesc+"</span></p>");
	}
	
	
}

function save_URL(url){
	newphotourl = url;
	//console.log("photo upload complete");
	$("#waiting").hide('fast');
	$.unblockUI();
}

function save_myURL(url){
	newphotourl = url;
	//console.log("photo upload complete");
	$("#waiting2").hide('fast');
	$.unblockUI();
}

var pictureSource;   // picture source
var destinationType; // sets the format of returned value 

// Wait for Cordova to connect with the device
//
document.addEventListener("deviceready",onDeviceReady,false);

function onDeviceReady() {
    pictureSource=navigator.camera.PictureSourceType;
    destinationType=navigator.camera.DestinationType;
}

// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
	//show div
	$("#waiting").show('fast');
	$.blockUI();
	
  // Uncomment to view the base64 encoded image data
  // console.log(imageData);

  // Get image handle
  //
  var smallImage = document.getElementById('smallImage');

  // Unhide image elements
  //
  //smallImage.style.display = 'block';

  // Show the captured photo
  // The inline CSS rules are used to resize the image
  //
  smallImage.src = "data:image/jpeg;base64," + imageData;

  upload_photo(imageData,save_URL);

  
}

function capturePhoto() {
    // Take picture using device camera and retrieve image as base64-encoded string
    navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
      destinationType: destinationType.DATA_URL, targetWidth:600, targetHeight:600 });
}

function getPhoto(source) {
    // Retrieve image file location from specified source
    navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50, 
    destinationType: destinationType.DATA_URL,
      sourceType: source, targetWidth:600, targetHeight:600 });
}




// Called when a photo is successfully retrieved
//
function onMyPhotoDataSuccess(imageData) {
	$("#waiting2").show('fast');
	$.blockUI();
  // Uncomment to view the base64 encoded image data
  // console.log(imageData);

  // Get image handle
  //
  var mySmallImage = document.getElementById('mySmallImage');

  // Unhide image elements
  //
  //smallImage.style.display = 'block';

  // Show the captured photo
  // The inline CSS rules are used to resize the image
  //
  mySmallImage.src = "data:image/jpeg;base64," + imageData;

  upload_photo(imageData,save_myURL);

  
}

function captureMyPhoto() {
    // Take picture using device camera and retrieve image as base64-encoded string
    navigator.camera.getPicture(onMyPhotoDataSuccess, onFail, { quality: 50,
      destinationType: destinationType.DATA_URL, targetWidth:600, targetHeight:600 });
}

function getMyPhoto(source) {
    // Retrieve image file location from specified source
    navigator.camera.getPicture(onMyPhotoDataSuccess, onFail, { quality: 50, 
    destinationType: destinationType.DATA_URL,
      sourceType: source, targetWidth:600, targetHeight:600 });
}

function onFail(message) {
    alert('Failed because: ' + message);
}






function loginsuccess(userdata){
	var msg = userdata.success;
	if (msg=="success"){
		user_id=userdata.user_id;
		//user_obj=userdata;
		$.cookie("user_id",user_id);
		
		$.cookie("user_id",user_id);
		window.location.href="#profile";
	}
	else{
		alert(msg);
	}
}

function regsuccess(result){
	console.log(result.success);
	console.log(result);
	window.location.href="#profile";
}

function doLogin(){
	var userid=$("#inputid").val();
	var password=$("#inputpw").val();
	login(userid,password,loginsuccess);
}

function doLogout(){
	inputid.value="";
	inputpw.value="";
	user_id="";
	user_obj="";
	$.cookie("user_id", null);
}

function doRegister(){
	
	var userid = $("#inputregid").val();
	var username = $("#inputname").val();
	var password=$("#inputregpw").val();
	var password2=$("#inputregpw2").val();
	var desc=$("#inputdesc").val();

	if (password == password2) register(username, password, newphotourl, desc, userid, regsuccess);
	else alert("Passwords Not Matched!");
	
}

function doFollow(){
	if (user_id==null)
		alert("login first");
	else if (user_id == survey_user_id)
		alert("It's your survey");
	else
		follow(user_id,survey_user_id,function(a){alert(a.success);});
}

function doPostComm(){
	if (user_id==""){
		alert("not logged in");
		return;
	}
	var comm = $("#commentarea").val();
	
	if (comm == "") alert("blank comment");
	else{
		post_comment(survey_id,user_id,user_obj.photo_url,comm,function(d){
			alert(d.success);
			commentarea.value="";
			updateCommentList();
		});
	}
}